import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import os
from path_manager import PathManager

class PathConfigTool:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("企微社群专用 - 路径配置工具")
        self.root.geometry("600x400")
        self.root.resizable(True, True)
        
        self.path_manager = PathManager()
        self.setup_ui()
        self.load_current_paths()
    
    def setup_ui(self):
        # 主框架
        main_frame = ttk.Frame(self.root, padding="10")
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 标题
        title_label = ttk.Label(main_frame, text="企微社群专用 - 路径配置", font=("Arial", 16, "bold"))
        title_label.pack(pady=(0, 20))
        
        # 说明文字
        info_text = """请配置企业微信的安装路径。程序会按顺序尝试这些路径，直到找到正确的企业微信可执行文件。"""
        info_label = ttk.Label(main_frame, text=info_text, wraplength=550, justify=tk.CENTER)
        info_label.pack(pady=(0, 20))
        
        # 路径列表框架
        paths_frame = ttk.LabelFrame(main_frame, text="路径列表", padding="10")
        paths_frame.pack(fill=tk.BOTH, expand=True, pady=(0, 20))
        
        # 创建Treeview来显示路径
        columns = ("序号", "路径", "状态")
        self.tree = ttk.Treeview(paths_frame, columns=columns, show="headings", height=8)
        
        # 设置列标题
        self.tree.heading("序号", text="序号")
        self.tree.heading("路径", text="路径")
        self.tree.heading("状态", text="状态")
        
        # 设置列宽
        self.tree.column("序号", width=50)
        self.tree.column("路径", width=400)
        self.tree.column("状态", width=100)
        
        # 添加滚动条
        scrollbar = ttk.Scrollbar(paths_frame, orient=tk.VERTICAL, command=self.tree.yview)
        self.tree.configure(yscrollcommand=scrollbar.set)
        
        self.tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        # 按钮框架
        button_frame = ttk.Frame(main_frame)
        button_frame.pack(fill=tk.X, pady=(0, 10))
        
        # 按钮
        ttk.Button(button_frame, text="添加路径", command=self.add_path).pack(side=tk.LEFT, padx=(0, 10))
        ttk.Button(button_frame, text="删除路径", command=self.delete_path).pack(side=tk.LEFT, padx=(0, 10))
        ttk.Button(button_frame, text="上移", command=self.move_up).pack(side=tk.LEFT, padx=(0, 10))
        ttk.Button(button_frame, text="下移", command=self.move_down).pack(side=tk.LEFT, padx=(0, 10))
        ttk.Button(button_frame, text="浏览文件", command=self.browse_file).pack(side=tk.LEFT, padx=(0, 10))
        
        # 保存和取消按钮
        save_frame = ttk.Frame(main_frame)
        save_frame.pack(fill=tk.X)
        
        ttk.Button(save_frame, text="保存配置", command=self.save_config, style="Accent.TButton").pack(side=tk.RIGHT, padx=(10, 0))
        ttk.Button(save_frame, text="取消", command=self.root.destroy).pack(side=tk.RIGHT)
    
    def load_current_paths(self):
        """加载当前路径到界面"""
        # 清空现有项目
        for item in self.tree.get_children():
            self.tree.delete(item)
        
        # 添加路径
        for i, path in enumerate(self.path_manager.wechat_paths, 1):
            status = "存在" if os.path.exists(path) else "不存在"
            self.tree.insert("", tk.END, values=(i, path, status))
    
    def add_path(self):
        """添加新路径"""
        path = filedialog.askopenfilename(
            title="选择企微社群专用可执行文件",
            filetypes=[("可执行文件", "*.exe"), ("所有文件", "*.*")]
        )
        if path:
            # 检查是否已存在
            existing_paths = [self.tree.item(item)["values"][1] for item in self.tree.get_children()]
            if path in existing_paths:
                messagebox.showwarning("警告", "该路径已存在！")
                return
            
            # 添加到列表
            status = "存在" if os.path.exists(path) else "不存在"
            self.tree.insert("", tk.END, values=(len(self.tree.get_children()) + 1, path, status))
    
    def delete_path(self):
        """删除选中的路径"""
        selected = self.tree.selection()
        if not selected:
            messagebox.showwarning("警告", "请先选择要删除的路径！")
            return
        
        if messagebox.askyesno("确认", "确定要删除选中的路径吗？"):
            self.tree.delete(selected)
            self.update_numbers()
    
    def move_up(self):
        """上移路径"""
        selected = self.tree.selection()
        if not selected:
            return
        
        item = selected[0]
        prev_item = self.tree.prev(item)
        if prev_item:
            # 交换位置
            prev_values = self.tree.item(prev_item)["values"]
            current_values = self.tree.item(item)["values"]
            
            self.tree.item(prev_item, values=(prev_values[0], current_values[1], current_values[2]))
            self.tree.item(item, values=(current_values[0], prev_values[1], prev_values[2]))
            
            self.tree.selection_set(prev_item)
    
    def move_down(self):
        """下移路径"""
        selected = self.tree.selection()
        if not selected:
            return
        
        item = selected[0]
        next_item = self.tree.next(item)
        if next_item:
            # 交换位置
            next_values = self.tree.item(next_item)["values"]
            current_values = self.tree.item(item)["values"]
            
            self.tree.item(next_item, values=(next_values[0], current_values[1], current_values[2]))
            self.tree.item(item, values=(current_values[0], next_values[1], next_values[2]))
            
            self.tree.selection_set(next_item)
    
    def browse_file(self):
        """浏览文件"""
        selected = self.tree.selection()
        if not selected:
            messagebox.showwarning("警告", "请先选择要修改的路径！")
            return
        
        path = filedialog.askopenfilename(
            title="选择企微社群专用可执行文件",
            filetypes=[("可执行文件", "*.exe"), ("所有文件", "*.*")]
        )
        if path:
            item = selected[0]
            values = list(self.tree.item(item)["values"])
            values[1] = path
            values[2] = "存在" if os.path.exists(path) else "不存在"
            self.tree.item(item, values=values)
    
    def update_numbers(self):
        """更新序号"""
        items = self.tree.get_children()
        for i, item in enumerate(items, 1):
            values = list(self.tree.item(item)["values"])
            values[0] = i
            self.tree.item(item, values=values)
    
    def save_config(self):
        """保存配置"""
        # 获取所有路径
        paths = []
        for item in self.tree.get_children():
            path = self.tree.item(item)["values"][1]
            if path and path not in paths:
                paths.append(path)
        
        if not paths:
            messagebox.showerror("错误", "至少需要配置一个路径！")
            return
        
        # 更新路径管理器
        self.path_manager.wechat_paths = paths
        
        # 保存到文件
        try:
            self.path_manager.save_config()
            messagebox.showinfo("成功", "配置已保存！")
            self.root.destroy()
        except Exception as e:
            messagebox.showerror("错误", f"保存配置时出错：{e}")
    
    def run(self):
        """运行配置工具"""
        self.root.mainloop()

if __name__ == "__main__":
    app = PathConfigTool()
    app.run()
